package com.udian.frame.code;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;


public class CreateCode {
	
	//连接数据库
	static String  url = "jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=utf8" ;
	static String  username = "root" ;   
	static String password = "fair" ; 
	
	private static Connection conn = null;
	
	
	
	public static void main1(String[] args) throws Exception {
		initConnection();
		
		List<Table> tableList = getTableList("sys");
		Project project = new Project();
		project.setComment("内评");
		project.setProjectName("frame");
		project.setProjectPath("D:\\dev\\workspace\\spring-cloud-client");
		
		project.setTableList(tableList);
		
		
		Map<String,List<Field>> map = new HashMap<String, List<Field>>();
		for(Table table : tableList){
			List<Column> columnList = getColumnList("sys",table.getName());
			List<Field> listField = new ArrayList<Field>();
			for(Column column : columnList){
				Field field = new Field();
				field.setName(column.getAlias());
				field.setRequire(String.valueOf((!column.isFlag())));
				field.setType(column.getXiaoYaoJiType());
				field.setDescription(column.getComment());
				if(column.getAlias().equals("id")||column.getAlias().equals("createTime")){
					continue;
				}
				listField.add(field);
			}
			map.put(table.getName(), listField);
		}
		
		List<Field> insurance = map.get("insur_record");

		List<Field> pay = map.get("insur_pay_record");
		Field fieldpay = new Field();
		fieldpay.setName("listInsurPayRecord");
		fieldpay.setType("array[object]");
		fieldpay.setDescription("保单交费列表");
		fieldpay.setChildren(pay);
		insurance.add(fieldpay);
		
		List<Field> operate = map.get("insur_operate_record");
		Field fieldoperate = new Field();
		fieldoperate.setName("listInsurOperateRecord");
		fieldoperate.setType("array[object]");
		fieldoperate.setDescription("保单操作列表");
		fieldoperate.setChildren(operate);
		insurance.add(fieldoperate);
		
		List<Field> additional = map.get("insur_additional_record");
		Field fieldadd = new Field();
		fieldadd.setName("listInsurAdditionalRecord");
		fieldadd.setType("array[object]");
		fieldadd.setDescription("附加保单列表");
		fieldadd.setChildren(additional);
		insurance.add(fieldadd);

		
		List<Field> user = map.get("insur_user");
		Field fieldInsur = new Field();
		fieldInsur.setName("listInsurRecord");
		fieldInsur.setType("array[object]");
		fieldInsur.setDescription("保单列表");
		fieldInsur.setChildren(insurance);
		user.add(fieldInsur);
		
		System.out.println(JSONObject.toJSONString(user));
		conn.close();
	}
	
	
	
	public static void main2(String[] args) throws Exception {
		initConnection();
		
		List<Table> tableList = getTableList("innereval-new");
		Project project = new Project();
		project.setComment("内评");
		project.setProjectName("innereval");
		project.setProjectPath("D:\\dev\\workspace\\spring-cloud-client");
		
		project.setTableList(tableList);

		for(Table table : tableList){
			List<Column> columnList = getColumnList("innereval-new",table.getName());
			table.setColumnList(columnList);
			String path = "D:\\dev\\workspace\\spring-cloud-client";
			
			Map<String,String> map = new HashMap<String,String>();
			map.put("entity.flt", path+"\\src\\main\\java\\com\\udian\\frame\\code\\file\\"+table.getAlias()+".java");
			map.put("xml.flt", path+"\\src\\main\\java\\com\\udian\\frame\\code\\file\\"+table.getAlias()+"Dao.xml");
	
			for(Map.Entry<String,String> entry : map.entrySet()){
				createFile(table,entry.getKey(),entry.getValue());
			}
		}
		conn.close();
	}
	
	
	
	
	public static void main(String[] args) throws Exception {
		initConnection();
		List<Column> columnList = getColumnList("sys","black_list_natural_person");
		Table table = new Table();
		table.setName("black_list_natural_person");
		table.setComment("黑名单自然人信息");
		table.setProjectName("sys");
		table.setProjectPath("sys");
		table.setAuthor("zhuwda@yonyou.com");
		table.setDate("2018-09-27");
		table.setVersion("V5.6.0");
		table.setPrefix("black_list");
		table.setPackagePath("com.yylending.rcp.data.blacklist");
		table.setColumnList(columnList);
		String path = "D:\\dev\\workspace\\spring-cloud-client";
		
		Map<String,String> map = new HashMap<String,String>();
//		map.put("entity.flt", path+"\\src\\main\\java\\com\\udian\\frame\\code\\file\\"+table.getAlias()+".java");
//		map.put("xml.flt", path+"\\src\\main\\java\\com\\udian\\frame\\code\\file\\"+table.getAliasObject()+".xml");
//		map.put("dao.flt", path+table.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+table.getProjectName()+"\\"+"dao\\line\\"+table.getAlias()+"Dao.java");
//		map.put("entity.flt", path+table.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+table.getProjectName()+"\\"+"model\\line\\"+table.getAlias()+".java");
//		map.put("entityDTO.flt", path+table.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+table.getProjectName()+"\\"+"model\\base\\dto\\"+table.getAlias()+"DTO.java");
//		map.put("service.flt", path+table.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+table.getProjectName()+"\\"+"service\\base\\"+table.getAlias()+"Service.java");
//		map.put("serviceImpl.flt", path+table.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+table.getProjectName()+"\\"+"service\\base\\impl\\"+table.getAlias()+"ServiceImpl.java");
//		map.put("controller.flt", path+table.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+table.getProjectName()+"\\"+"web\\"+table.getAlias()+"Controller.java");
//		map.put("test.flt", path+table.getProjectPath()+"\\src\\test\\java\\com\\udiannet\\"+table.getProjectName()+"\\"+"test\\"+table.getAlias()+"ApiTest.java");
//
		String filepath = "D:\\dev\\workspace\\spring-cloud-client\\file\\";
		map.put("entity.flt",filepath+table.getAlias()+".java");
		map.put("xml.flt", filepath+table.getAliasObject()+".xml");
		map.put("serviceImpl.flt", filepath+table.getAlias()+"Service.java");
		map.put("controller.flt", filepath+table.getAlias()+"Controller.java");
		map.put("dao.flt", filepath+table.getAlias()+"Dao.java");

		for(Map.Entry<String,String> entry : map.entrySet()){
			createFile(table,entry.getKey(),entry.getValue());
		}
		
		conn.close();
	}
	
	
	
/*	public static void main(String[] args) throws Exception {
		initConnection();
		
		List<Table> tableList = getTableList("innereval-new");
		Project project = new Project();
		project.setComment("内评");
		project.setProjectName("innereval");
		project.setProjectPath("D:\\dev\\workspace\\spring-cloud-client");
		
		project.setTableList(tableList);

		for(Table table : tableList){
			List<Column> columnList = getColumnList("innereval","insurance_user");
			table.setColumnList(columnList);
			String path = "D:\\dev\\workspace\\spring-cloud-client";
			
			Map<String,String> map = new HashMap<String,String>();
			map.put("entity.flt", path+"\\src\\main\\java\\com\\udian\\frame\\code\\file\\"+table.getAlias()+".java");
			map.put("xml.flt", path+"\\src\\main\\java\\com\\udian\\frame\\code\\file\\"+table.getAliasObject()+".xml");
	
			for(Map.Entry<String,String> entry : map.entrySet()){
				createFile(table,entry.getKey(),entry.getValue());
			}
		}
		conn.close();
	}*/
	
	
	
	
//	public static void main(String[] args) throws Exception {
//		initConnection();
//		
//		List<Table> tableList = getTableList("db_line_szjw");
//		
//	
//		Project project = new Project();
//		project.setComment("交委线路");
//		project.setProjectName("linenet");
//		project.setProjectPath("line-net");
//		
//		project.setTableList(tableList);
//		String path = "D:\\dev\\workspace\\";
//		for(Table table : tableList){
//			
//			Map<String,String> map = new HashMap<>();
//			table.setProjectName(project.getProjectName());
//			table.setProjectPath(project.getProjectPath());
//			map.put("xml.flt", path+project.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+project.getProjectName()+"\\"+"dao\\base\\xml\\"+table.getAliasObject()+".xml");
//			map.put("entity.flt", path+project.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+project.getProjectName()+"\\"+"model\\base\\"+table.getAlias()+".java");
//			/*map.put("entityDTO.flt", path+project.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+project.getProjectName()+"\\"+"model\\dto\\"+table.getAlias()+"DTO.java");
//			map.put("dao.flt", path+project.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+project.getProjectName()+"\\"+"dao\\"+table.getAlias()+"Dao.java");
//			map.put("service.flt", path+project.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+project.getProjectName()+"\\"+"service\\"+table.getAlias()+"Service.java");
//			map.put("serviceImpl.flt", path+project.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+project.getProjectName()+"\\"+"service\\impl\\"+table.getAlias()+"ServiceImpl.java");
//			map.put("controller.flt", path+project.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+project.getProjectName()+"\\"+"web\\"+table.getAlias()+"Controller.java");
//			map.put("test.flt", path+project.getProjectPath()+"\\src\\test\\java\\com\\udiannet\\"+project.getProjectName()+"\\"+"test\\"+table.getAlias()+"ApiTest.java");
//*/			
//			//map.put("confluenceList.flt", "D:\\dev\\workspace\\line-net\\confluence.txt");
//			
//			for(Map.Entry<String,String> entry : map.entrySet()){
//				
//					createFile(table,entry.getKey(),entry.getValue());
//				
//			}
//		}
//		
//		conn.close();
//	}
//	
	
	/*public static void main(String[] args) throws Exception {
		initConnection();
		
		List<Table> tableList = getTableList("db_base_data");
		
		Project project = new Project();
		project.setComment("基础数据");
		project.setProjectName("linenet");
		project.setProjectPath("line-net");
		
		project.setTableList(tableList);
		
			
//			Map<String,String> map = new HashMap<>();
//			table.setProjectName(project.getProjectName());
//			table.setProjectPath(project.getProjectPath());
//			map.put("xml.flt", path+project.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+project.getProjectName()+"\\"+"dao\\xml\\"+table.getAliasObject()+".xml");
//			map.put("entity.flt", path+project.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+project.getProjectName()+"\\"+"model\\"+table.getAlias()+".java");
//			map.put("entityDTO.flt", path+project.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+project.getProjectName()+"\\"+"model\\dto\\"+table.getAlias()+"DTO.java");
//			map.put("dao.flt", path+project.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+project.getProjectName()+"\\"+"dao\\"+table.getAlias()+"Dao.java");
//			map.put("service.flt", path+project.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+project.getProjectName()+"\\"+"service\\"+table.getAlias()+"Service.java");
//			map.put("serviceImpl.flt", path+project.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+project.getProjectName()+"\\"+"service\\impl\\"+table.getAlias()+"ServiceImpl.java");
//			map.put("controller.flt", path+project.getProjectPath()+"\\src\\main\\java\\com\\udiannet\\"+project.getProjectName()+"\\"+"web\\"+table.getAlias()+"Controller.java");
//			map.put("test.flt", path+project.getProjectPath()+"\\src\\test\\java\\com\\udiannet\\"+project.getProjectName()+"\\"+"test\\"+table.getAlias()+"ApiTest.java");
//			

			try {
				createFile(project,"confluenceList.flt","D:\\dev\\workspace\\line-net\\confluence.txt");
			} catch (Exception e) {
				
			}
		conn.close();
	}*/
	
	private static void createFile(Project project,String flt,String file)
			throws IOException, TemplateNotFoundException, MalformedTemplateNameException, ParseException,
			FileNotFoundException, TemplateException, UnsupportedEncodingException {
	
		// 设置模板的home目录，默认从此目录获取模板（此设置只需在应用中设置一次） 
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setDirectoryForTemplateLoading(new File("D:\\dev\\workspace\\spring-cloud-client\\src\\main\\java\\com\\udian\\frame\\code\\flt\\"));
        cfg.setDefaultEncoding("UTF-8");
       
        
        // 获取模板
        Template temp = cfg.getTemplate(flt);
        
        // 将模板和数据模型合并 
        FileOutputStream fos = new FileOutputStream(new File(file));
       
        StringWriter out = new StringWriter(); 
        temp.process(project, out);
        
        out.flush();
		System.out.println(1111);
		String s = out.toString().replaceAll("\\\\", "");
		fos.write(s.getBytes("utf-8"));
		fos.close();
	}
	
	
	private static void createFile(Table table,String flt,String file)
			throws Exception{
	
		// 设置模板的home目录，默认从此目录获取模板（此设置只需在应用中设置一次） 
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setDirectoryForTemplateLoading(new File("D:\\dev\\workspace\\spring-cloud-client\\src\\main\\java\\com\\udian\\frame\\code\\flt\\"));
        cfg.setDefaultEncoding("UTF-8");
       
        
        // 获取模板
        Template temp = cfg.getTemplate(flt);
        
        // 将模板和数据模型合并 
        FileOutputStream fos = new FileOutputStream(new File(file));
       
        StringWriter out = new StringWriter(); 
        temp.process(table, out);
        
        out.flush();
		System.out.println();
		String s = out.toString().replaceAll("\\\\", "");
		fos.write(s.getBytes("utf-8"));
		fos.close();
	}
	
	private static List<Table> getTableList(String databaseName) throws SQLException {
		String sql = "SELECT  table_name , table_comment FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ?";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, databaseName);
		ResultSet resultSet = ps.executeQuery();
		List<Table> tableList = new ArrayList<Table>();
		while (resultSet.next()) {
			Table table = new Table();
			String name = resultSet.getString("table_name");
			table.setName(name);
			table.setComment(resultSet.getString("table_comment"));
			List<Column> columnList = getColumnList(databaseName, name);
			table.setColumnList(columnList);
			tableList.add(table);
		}
		return tableList;
	}

	private static List<Column> getColumnList(String databaseName,String tableName) throws SQLException {
		String sql = "SELECT column_name , data_type,column_comment , character_maximum_length,is_nullable  FROM information_schema.columns WHERE table_schema = ? AND table_name = ? ";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, databaseName);
		ps.setString(2, tableName);
		ResultSet resultSet = ps.executeQuery();
		List<Column> columnList = new ArrayList<Column>();
		while (resultSet.next()) {
			Column column = new Column();
			column.setName(resultSet.getString("column_name"));
			column.setType(resultSet.getString("data_type"));
			column.setComment(resultSet.getString("column_comment"));
			column.setMaxLength(resultSet.getString("character_maximum_length")==null ?"" : resultSet.getString("character_maximum_length"));
			
			column.setFlag(resultSet.getString("is_nullable").equals("NO"));
			resultSet.getInt("character_maximum_length");
			columnList.add(column);
		}
		return columnList;
	}
	
	public static void initConnection(){
		 //加载驱动
        String className = "com.mysql.jdbc.Driver"; 
        try {
            Class.forName(className);
            System.out.println("1、加载成功");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();System.out.println("找不到驱动程序类 ，加载驱动失败！");   
            e.printStackTrace() ;   
        }
        try{   
            conn = DriverManager.getConnection(url, username, password);
            System.out.println("2、连接成功");
        }catch(SQLException se){   
            System.out.println("数据库连接失败！");   
            se.printStackTrace() ;   
        }
	}
	
	
	
}
